package com.hyl.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.hyl.common.exception.NoStockException;
import com.hyl.common.to.mq.OrderTo;
import com.hyl.common.to.mq.StockDetailTo;
import com.hyl.common.to.mq.StockLockedTo;
import com.hyl.common.utils.R;
import com.hyl.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.hyl.gulimall.ware.entity.WareOrderTaskEntity;
import com.hyl.gulimall.ware.feign.OrderFeignService;
import com.hyl.gulimall.ware.feign.ProductFeignService;
import com.hyl.gulimall.ware.service.WareOrderTaskDetailService;
import com.hyl.gulimall.ware.service.WareOrderTaskService;
import com.hyl.gulimall.ware.vo.*;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyl.common.utils.PageUtils;
import com.hyl.common.utils.Query;

import com.hyl.gulimall.ware.dao.WareSkuDao;
import com.hyl.gulimall.ware.entity.WareSkuEntity;
import com.hyl.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;



@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        /*1.判断是否有这个库存记录*/
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(
                new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.isEmpty()) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            /*远程获得sku的名字*/
            try {
                /*为了不让skuName这个冗余字段影响整个事物，用try,catch,如果失败不需要回滚*/
                /*TODO：其他方法？高级部分*/
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(wareSkuEntity);
        } else {

            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();

            skuHasStockVo.setSkuId(skuId);
            Long count = baseMapper.getSkuStock(skuId);
            skuHasStockVo.setHasStock(count != null && count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 1.本地事务
     * 为某个订单锁库存，默认是运行时异常都会回滚，也可以显式指定rollbackFor
     * <p>
     * 2.分布式事务
     * <p>
     * 库存解锁场景
     * i.下单成功，订单过期没有支付被系统自动取消或用户手动取消
     * ii. 下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，锁定的库存需要自动解锁
     *
     * @param wareSkuLockVo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        //1. 保存库存工作单详情,方便追溯
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskService.save(taskEntity);


        //2. 按照下单的收货地址，找到一个就近的仓库，锁定库存
        //2.1简化：找到每个商品在哪个仓库有库存
        List<OrderItemVo> lockItems = wareSkuLockVo.getLocks();
        List<SkuWareHasStock> skuWareHasStocks = lockItems.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //找出那些仓库有货
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2.2锁定库存
        //全局标识量，sku索库存是否成功
        //boolean allLock = true;
        for (SkuWareHasStock hasStock : skuWareHasStocks) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                //仓库为空
                throw new NoStockException(skuId);
            }
            //如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发给MQ
            //如果某一个商品库存锁定失败，前面保存的工作单就回滚了。该失败的商品
            for (Long wareId : wareIds) {
                //返回1成功(1行受影响),返回0失败(0行受影响),update的返回结果，几行数据受影响
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    skuStocked = true;
                    //给MQ发消息，告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(
                            null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(detailEntity);
                    StockLockedTo to = new StockLockedTo();
                    StockDetailTo detailTo = new StockDetailTo();
                    to.setId(taskEntity.getId());
                    BeanUtils.copyProperties(detailEntity, detailTo);
                    //防止回滚之后找不到数据,所以保存每个完整锁库存信息
                    to.setDetail(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", to);
                    break;
                } else {
                    //当前仓库库存不足，尝试下一个仓库

                }
            }
            if (skuStocked == false) {
                //当前商品所有仓库都无货(没锁住库存)
                throw new NoStockException(skuId);
            }
        }

        //全部锁定成功
        return true;
    }


    /**
     * 内部类封装要所库存的sku在哪些仓库有库存
     */
    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

    /**
     * 库存解锁场景
     * 1.订单成功
     * i.下单成功，订单过期没有支付被系统自动取消或用户手动取消
     * ii. 下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，锁定的库存需要自动解锁
     * 2.订单不成功
     * i.锁库存失败
     * <p>
     * 1和2的区别在于2本来锁库存就失败了，无需再解锁。而1锁库存成功，在有其他业务失败的情况下需要解锁
     * 如何判断1需不需要解锁呢，根据订单的状态
     *
     * !!!如果解锁库存的消息失败，一定要告诉服务解锁失败。（手动确认机制）
     * @param
     * @return
     */
    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if (detailEntity != null) {
            //情况1 先拿到订单信息
            Long orderTaskId = to.getId();
            WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getById(orderTaskId);
            String orderSn = wareOrderTaskEntity.getOrderSn();
            //根据唯一的订单号查询订单服务中该订单的状态
            R orderStatusR = orderFeignService.getOrderStatus(orderSn);
            if (orderStatusR.getCode() == 0) {
                OrderVo data = orderStatusR.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus() == 4) {
                    //没有这个订单 或者 有订单但订单状态是已取消,解锁库存
                    //只有状态是1(sku锁定状态),才能解锁
                    if (detailEntity.getLockStatus() == 1) {
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                        //解锁成功，接受消息
                        //channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                    }

                    //这里将对消息的回复的情况放在Listener中去处理了，else这里其他情况直接抛异常
                }else {
                    //远程服务失败，拒绝消息，重新放回消息队列
                    //channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
                    throw new RuntimeException("远程服务调用失败");
                }
            } else {
                //情况2 无需解锁,直接接受消息
                //channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

            }
        }
    }



    /**
     *防止因为订单服务卡顿，导致订单状态信息一直改不了，库存消息优先到期。查订单状态是新建状态，什么都不做就走了
     * 导致订单的卡顿，永远解锁不了
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查询最新库存状态,防止重复解锁库存
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        //根据库存工作单，查询该单下每一个没被解锁的sku库存
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        //库存解锁
        wareSkuDao.unlockStock(skuId, wareId, num);
        //更新库存工作单状态 1(已锁定)→2(已解锁)
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }
}
